/*
 * @Author: 2678187122@qq.com
 * @Date: 2023-09-05 15:42:35
 * @LastEditTime: 2023-12-11 17:10:41
 * @LastEditors: 2678187122@qq.com
 * @Description: 全局公共工具
 */
import { listByCode } from '@/api/system/data-dict'
import store from '@/store'

// 获取数据字典
export function getDictInfo(code) {
  return new Promise(resolve => {
  // 通过系统配置判断数据字典取值方式
    const val = store.state.settings.globalData && store.state.settings.globalData['data_dict_get_way']
    if (val === '1') {
      listByCode({ code }).then(res => {
        resolve(res && res.data)
      })
    } else {
      const arr = store.state.settings.dictItem && Object.keys(store.state.settings.dictItem).map(code => {
        return {
          code,
          children: store.state.settings.dictItem[code]
        }
      })
      arr.forEach(item => {
        if (item.code === code) {
          resolve(item.children)
        }
      })
    }
  })
}

// 判断图片地址是否需要补全
export function getImageUrl(url) {
  if (!url) return ''
  // 检查是否已包含 http:// 或 https://
  if (/^https?:\/\//.test(url)) {
    return url // 已包含前缀，直接返回
  }
  return store.state.settings.baseUrl + url
}

// 动态引入图片
export function getIconUrl(icon) {
  return new URL(icon, import.meta.url).href
}

// 16进制转RGBA，可设置透明度
export function hexToRgba(hex, alpha) {
  const r = parseInt(hex.slice(1, 3), 16)
  const g = parseInt(hex.slice(3, 5), 16)
  const b = parseInt(hex.slice(5, 7), 16)
  return `rgba(${r}, ${g}, ${b}, ${alpha})`
}

